package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.config.EwcrmProperties;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.entity.AUserNotice;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.file.FileUtil;
import com.chhuang.ewcrm.service.AUserNoticeService;
import com.chhuang.ewcrm.service.SysUserService;
import com.chhuang.ewcrm.string.Md5Util;
import com.chhuang.ewcrm.vo.ResultBean;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * (SysUser)表控制层
 *
 * @author chhuang
 * @since 2020-09-25 09:35:02
 */
@RestController
@RequestMapping("/service/sysUser")
public class SysUserController {
    Logger logger= LoggerFactory.getLogger(SysUserController.class);

    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;
    @Resource
    private AUserNoticeService aUserNoticeService;

    @Autowired
    private EwcrmProperties ewcrmProperties;

    @Autowired
    private HttpSession session;

    /**
     * 检验用户名不为空或者是否已存在
     * @param username
     * @return
     */
    @GetMapping("/checkUsername")
    public ResultBean<?> checkUsername(String userId, String username){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if("sessionId".equals(userId)){
            userId = getLoginUserId();
        }

        if(StringUtils.isNotEmpty(username)){
            SysUser u = new SysUser();
            u.setUsername(username);
            List<SysUser> users = this.sysUserService.query(u);
            if(users==null || users.isEmpty() || users.get(0).getUserId().equals(userId)) //用户名不存在
                resultBean.setSuccess(true);
            else
                resultBean.setMessage("用户名已存在");
        }else
            resultBean.setMessage("用户名不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 检验用户手机号不为空或者已存在
     * @param userphone
     * @return
     */
    @GetMapping("/checkPhone")
    public ResultBean<?> checkPhone(String userId, String userphone){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if("sessionId".equals(userId)){
            userId = getLoginUserId();
        }

        if(StringUtils.isNotEmpty(userphone)) {//手机号不为空
            SysUser u = new SysUser();
            u.setUserphone(userphone);
            List<SysUser> users = this.sysUserService.query(u);
            if (users == null || users.isEmpty() || users.get(0).getUserId().equals(userId)) //手机号不存在
                resultBean.setSuccess(true);
            else
                resultBean.setMessage("手机号已存在");
        }else
            resultBean.setMessage("手机号不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 检验邮箱号不为空或者已存在
     * @param email
     * @return
     */
    @GetMapping("/checkEmail")
    public ResultBean<?> checkEmail(String userId, String email){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);

        if("sessionId".equals(userId)){
            userId = getLoginUserId();
        }

        if(StringUtils.isNotEmpty(email)) {//邮箱号允许为空
            SysUser u = new SysUser();
            u.setEmail(email);
            List<SysUser> users = this.sysUserService.query(u);
            if(users!=null && !users.isEmpty() && !users.get(0).getUserId().equals(userId)) { //邮箱已存在
                resultBean.setSuccess(false);
                resultBean.setMessage("邮箱已存在");
            }
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     *获取登录用户编号
     * @return
     */
    private String getLoginUserId(){
        String userId = null;
        Object obj = session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
        if(obj!=null){
            SysUser sessionUser = (SysUser) obj;
            userId = sessionUser.getUserId();
        }
        return userId;
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/removeOne/{userId}")
    public ResultBean<?> removeOne(@PathVariable("userId") String userId){
        ResultBean<?> resultBean = new ResultBean<>();
        if(StringUtils.isNotEmpty(userId)){
            //删除用户头像
            deleteUserphoto(userId);
            //删除数据
            resultBean.setSuccess(this.sysUserService.deleteById(userId));
            if(resultBean.isSuccess()) {
                AUserNotice aUserNotice = new AUserNotice();
                aUserNotice.setUserId(userId);
                aUserNoticeService.deleteByEntity(aUserNotice);
            }
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 根据id列表批量删除
     * @param userIds
     * @return
     */
    @PutMapping("/removeList")
    public ResultBean<?> removeList(@RequestBody List<String> userIds){
        ResultBean<?> resultBean = new ResultBean<>();
        if(userIds!=null && !userIds.isEmpty()){
            //删除用户头像
            userIds.forEach(this::deleteUserphoto);
            resultBean.setSuccess(this.sysUserService.deleteByIds(userIds)>0);
            if(resultBean.isSuccess()){
                userIds.forEach(id-> {
                    AUserNotice aUserNotice = new AUserNotice();
                    aUserNotice.setUserId(id);
                    aUserNoticeService.deleteByEntity(aUserNotice);
                });
            }
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 删除用户头像
     * @param userId
     */
    private void deleteUserphoto(String userId){
        SysUser user = this.sysUserService.queryById(userId);
        if(user!=null && StringUtils.isNotEmpty(user.getUserphoto())){
            String filename = user.getUserphoto().substring(EwcrmConstants.UPLOAD_URL.length());
            String filepath = ewcrmProperties.getUploadPath()+filename;
            File file = new File(filepath);
            FileUtils.deleteQuietly(file);
        }
    }

    /**
     * 重置密码
     * @return
     */
    @PostMapping("/resetPassword")
    public ResultBean<?> resetPassword(String userId){
        ResultBean<?> resultBean = new ResultBean<>();
        SysUser user = sysUserService.queryById(userId);
        user.setPassword(Md5Util.md5(user.getUserphone(), Md5Util.md5(user.getUsername())));
        user.setModifyTime(new Date());
        this.sysUserService.update(user);
        resultBean.setSuccess(true);
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 根据id列表重置密码
     * @param userIds
     * @return
     */
    @PutMapping("/resetPasswords")
    public ResultBean<?> resetPasswords(@RequestBody List<String> userIds){
        ResultBean<?> resultBean = new ResultBean<>();
        if(userIds!=null && !userIds.isEmpty()){
            List<SysUser> users = new LinkedList<>();
            for(String id: userIds){
                SysUser user = this.sysUserService.queryById(id);
                if(user!=null){
                    user.setPassword(Md5Util.md5(user.getUserphone(), Md5Util.md5(user.getUsername())));
                    user.setModifyTime(new Date());
                    users.add(user);
                }
            }
            resultBean.setSuccess(this.sysUserService.updateBatch(users)>0);
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 修改用户信息
     * @param sysUser
     * @return
     * @throws IOException
     */
    @PutMapping("/editOne")
    public ResultBean<SysUser> editOne(@RequestBody SysUser sysUser){
        ResultBean<SysUser> resultBean = new ResultBean<SysUser>();
        resultBean.setSuccess(false);
        if(sysUser!=null) {
            if (StringUtils.isEmpty(sysUser.getUserId())) { //添加
                if(checkUsername(null,sysUser.getUsername()).isSuccess() &&
                        checkPhone(null,sysUser.getUserphone()).isSuccess() &&
                        checkEmail(null,sysUser.getEmail()).isSuccess()){
                    //密码默认是手机号
                    sysUser.setPassword(Md5Util.md5(sysUser.getUserphone(), Md5Util.md5(sysUser.getUsername())));
                    Date now = new Date();
                    sysUser.setCreateTime(now);
                    sysUser.setModifyTime(now);
                    sysUser = this.sysUserService.insert(sysUser);
                    resultBean.setData(sysUser);
                    resultBean.setSuccess(resultBean.getData()!=null);
                }else {
                    resultBean.setSuccess(false);
                    resultBean.setMessage("参数不能为空，或者用户名、手机号、邮箱号已存在");
                }
            } else{ //修改
                SysUser user = sysUserService.queryById(sysUser.getUserId());

                if (user != null && checkUsername(sysUser.getUserId(), sysUser.getUsername()).isSuccess()
                        && checkPhone(sysUser.getUserId(), sysUser.getUserphone()).isSuccess()
                        && checkEmail(sysUser.getUserId(), sysUser.getEmail()).isSuccess()) {
//                    user.setUsername(sysUser.getUsername());不能修改用户名，或者 密码需要初始化
                    user.setFullname(sysUser.getFullname());
                    user.setUserphone(sysUser.getUserphone());
                    user.setUsersphone(sysUser.getUsersphone());
                    user.setRoleId(sysUser.getRoleId());
                    user.setRoleName(sysUser.getRoleName());
                    user.setEmail(sysUser.getEmail());
                    user.setStatus(sysUser.getStatus());
                    user.setModifyTime(new Date());
                    sysUser = this.sysUserService.update(user);
                    resultBean.setData(sysUser);
                    resultBean.setSuccess(resultBean.getData()!=null);
                } else
                    resultBean.setMessage("没有找到用户，或者用户名、手机号、邮箱号已存在");
            }
        } else
            resultBean.setMessage("参数不能为空");
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 用户信息保存成功后，上传头像
     * @param userId
     * @param userphoto
     * @return
     */
    @PostMapping("/uploadPhoto")
    public ResultBean<String> uploadPhoto(String userId, MultipartFile userphoto) throws IOException {
        ResultBean<String> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(userId) && userphoto!=null && !userphoto.isEmpty() ){
            SysUser sysUser = sysUserService.queryById(userId);
            if(sysUser!=null) {
                String filename = userphoto.getOriginalFilename();//原文件名
                String suffixName = FileUtil.getFileSuffix(filename);//后缀名
                filename = "userphotos/" + sysUser.getUsername() + "." + suffixName;
                String userphotoPath = ewcrmProperties.getUploadPath() + filename;

                File file = new File(userphotoPath);
                FileUtil.makeFilePath(file);
                userphoto.transferTo(file);

                sysUser.setUserphoto(EwcrmConstants.UPLOAD_URL + filename);
                sysUser.setModifyTime(new Date());
                sysUser = this.sysUserService.update(sysUser);
                resultBean.setData(sysUser.getUserphoto());
                resultBean.setSuccess(true);

                //修改个人信息时，更新session
                Object obj = session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
                if(obj!=null){
                    SysUser sessionUser = (SysUser) obj;
                    if(sessionUser.getUserId().equals(userId)) {
                        sessionUser.setUserphoto(sysUser.getUserphoto());
                        session.setAttribute(EwcrmConstants.SessionConst.SYS_USER, sessionUser);
                    }
                }
            }else{
                resultBean.setMessage("用户不存在");
            }
        }else {
            resultBean.setMessage("参数不能为空");
        }

        return resultBean;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param userId 主键
     * @return 单条数据
     */
    @GetMapping("/getOne")
    public ResultBean<SysUser> getOne(String userId) {
        ResultBean<SysUser> resultBean = new ResultBean<SysUser>();
        resultBean.setSuccess(false);
        if(StringUtils.isNotEmpty(userId)){
            resultBean.setSuccess(true);
            resultBean.setData(this.sysUserService.queryById(userId));
        }else{
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 查询用户列表
     * @param queryBean
     * @return
     */
    @PostMapping("/queryPage")
    public ResultBean<PageInfo<SysUser>> query(@RequestBody QueryBean<SysUser> queryBean){
        logger.debug(queryBean.toString());
        ResultBean<PageInfo<SysUser>> resultBean = new ResultBean<PageInfo<SysUser>>();

        PageInfo<SysUser> pageInfo = null;
        List<SysUser> users = null;
        if(queryBean!=null) {
            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = sysUserService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = sysUserService.search(queryBean.getSearch(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
            resultBean.setSuccess(true);
            resultBean.setCode(queryBean.getDraw());
        }else {
            resultBean.setSuccess(false);
            resultBean.setMessage("参数不为空");
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 获取登录用户信息
     * @return
     */
    @GetMapping("/getLoginUser")
    public ResultBean<SysUser> getLoginUser(){
        ResultBean<SysUser> resultBean = new ResultBean<SysUser>();

        SysUser sessionUser = (SysUser) session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
        if (sessionUser != null) {
            resultBean.setData(sessionUser);
            resultBean.setSuccess(true);
        }else{
            resultBean.setSuccess(false);
            resultBean.setMessage("你还没有登录");
        }

        return resultBean;
    }

    /**
     * 修改自己的密码
     * @param oldPassword
     * @param password
     * @param confirmPassword
     * @return
     */
    @PostMapping("/resetUserPassword")
    public ResultBean<?> resetUserPassword( String oldPassword, String password, String confirmPassword){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(oldPassword)
                && StringUtils.isNotEmpty(password)
                && StringUtils.isNotEmpty(confirmPassword)) {
            Object obj = session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
            if (obj != null) {
                SysUser sessionUser = (SysUser)obj;
                if (confirmPassword.equals(password)) {
                    SysUser user = sysUserService.queryById(sessionUser.getUserId());
                    oldPassword = Md5Util.md5(oldPassword, Md5Util.md5(user.getUsername()));
                    if(user.getPassword().equals(oldPassword)) {
                        user.setPassword(Md5Util.md5(password, Md5Util.md5(user.getUsername())));
                        this.sysUserService.update(user);
                        resultBean.setSuccess(true);
                    }else {
                        resultBean.setMessage("原密码不正确");
                    }
                } else {
                    resultBean.setMessage("新密码与确认密码不一致");
                }
            } else {
                resultBean.setMessage("你还没有登录");
            }
        }else {
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 修改自己的信息
     * @param sysUser
     * @return
     */
    @PutMapping("/editUserInfo")
    public ResultBean<SysUser> editUserInfo(@RequestBody SysUser sysUser){
        ResultBean<SysUser> resultBean = new ResultBean<SysUser>();
        resultBean.setSuccess(false);

        Object obj = session.getAttribute(EwcrmConstants.SessionConst.SYS_USER);
        if (obj!=null && sysUser!=null) {
            SysUser sessionUser = (SysUser)obj;
            SysUser user = sysUserService.queryById(sessionUser.getUserId());

            if (user != null && checkUsername(user.getUserId(), sysUser.getUsername()).isSuccess()
                    && checkPhone(user.getUserId(), sysUser.getUserphone()).isSuccess()
                    && checkEmail(user.getUserId(), sysUser.getEmail()).isSuccess()) {
                //密码默认不修改
//                user.setUsername(sysUser.getUsername());不能修改用户名，或者 密码需要初始化
                user.setFullname(sysUser.getFullname());
                user.setUserphone(sysUser.getUserphone());
                user.setUsersphone(sysUser.getUsersphone());
                user.setUserphoto(sysUser.getUserphoto());
                user.setEmail(sysUser.getEmail());
                user.setModifyTime(new Date());
                sessionUser = this.sysUserService.update(user);
                resultBean.setData(sessionUser);
                resultBean.setSuccess(true);

                sessionUser.setPassword(null);
                session.setAttribute(EwcrmConstants.SessionConst.SYS_USER, sessionUser);
            }else
                resultBean.setMessage("用户不存在，或者用户名、手机号、邮箱号已存在");
        }else
            resultBean.setMessage("参数不为空，或者你还没有登录");

        logger.debug(resultBean.toString());
        return resultBean;
    }
}